package com.example.shiro.filter;

import com.example.shiro.token.JwtToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 过滤器，继承BasicHttpAuthenticationFilter
 * 不需要配置类注解，因为，这个filter直接写完是没有作用的！
 * 需要把它通过配置类的形式，注入到SecurityManager中！
 *
 * @author fyx
 */
public class ShiroFilter extends BasicHttpAuthenticationFilter {
    private static final String AUTH_HEADER = "authorization";

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        //这里如果为true将直接放行 进入controller请求，不通过shiro的过滤器链
        return super.preHandle(request, response);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginAttempt(request, response)) {
            if (executeLogin(request, response)) {
                return true;
            }
        }
        response401(request, response);
        return false;
    }

    private void response401(ServletRequest request, ServletResponse response) {
        try {
            request.getRequestDispatcher("/status/401").forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        String authHeader = ((HttpServletRequest) request).getHeader(AUTH_HEADER);
        return authHeader != null;
    }

    /**
     * 真正执行登录的地方
     *
     * @param request  传入的request
     * @param response 传出的response
     * @return 是否成功
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest request1 = (HttpServletRequest) request;
        //第一套方法：从请求头中获取，authorization，对象 有这个对象则表示可以认证
        String authorization = request1.getHeader(AUTH_HEADER);
        //json转对象
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(new JwtToken(authorization));
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
